package cz.data.domain.metadata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cz.data.common.mybatis.BaseServiceImpl;
import cz.data.common.exception.DataException;
import cz.data.common.utils.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cz.data.domain.metadata.dao.MetadataColumnDao;
import cz.data.domain.metadata.mapstruct.MetadataColumnMapper;
import cz.data.domain.metadata.model.dto.MetadataColumnDto;
import cz.data.domain.metadata.model.entity.MetadataColumnEntity;
import cz.data.domain.metadata.model.entity.MetadataSourceEntity;
import cz.data.domain.metadata.model.entity.MetadataTableEntity;
import cz.data.domain.metadata.model.enums.DataLevel;
import cz.data.domain.metadata.model.query.MetadataColumnQuery;
import cz.data.domain.metadata.model.query.MetadataTableQuery;
import cz.data.domain.metadata.model.vo.MetadataTreeVo;
import cz.data.domain.metadata.service.MetadataAuthorizeService;
import cz.data.domain.metadata.service.MetadataColumnService;
import cz.data.domain.metadata.service.MetadataSourceService;
import cz.data.domain.metadata.service.MetadataTableService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MetadataColumnServiceImpl extends BaseServiceImpl<MetadataColumnDao, MetadataColumnEntity> implements MetadataColumnService {

    @Autowired
    private MetadataColumnDao metadataColumnDao;

    @Autowired
    private MetadataColumnMapper metadataColumnMapper;

    @Autowired
    MetadataSourceService metadataSourceService;
    @Lazy
    @Autowired
    MetadataTableService metadataTableService;
    @Autowired
    MetadataAuthorizeService metadataAuthorizeService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public MetadataColumnEntity saveMetadataColumn(MetadataColumnDto metadataColumnDto) {
        MetadataColumnEntity metadataColumn = metadataColumnMapper.toEntity(metadataColumnDto);
        metadataColumnDao.insert(metadataColumn);
        return metadataColumn;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MetadataColumnEntity updateMetadataColumn(MetadataColumnDto metadataColumnDto) {
        MetadataColumnEntity metadataColumn = metadataColumnMapper.toEntity(metadataColumnDto);
        metadataColumnDao.updateById(metadataColumn);
        return metadataColumn;
    }

    @Override
    public MetadataColumnEntity getMetadataColumnById(String id) {
        return super.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMetadataColumnById(String id) {
        metadataColumnDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMetadataColumnBatch(List<String> ids) {
        metadataColumnDao.deleteBatchIds(ids);
    }

    @Override
    public void deleteMetadataColumnByTableId(String id) {
        List<MetadataColumnEntity> columns = getMetadataColumnByTableId(id);
        List<String> ids = columns.stream().map(MetadataColumnEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)) {
            this.deleteMetadataColumnBatch(ids);
        }
    }

    @Override
    public List<MetadataTreeVo> getDataMetadataTree(String level, MetadataColumnQuery metadataColumnQuery) {
        List<MetadataSourceEntity> sourceList = metadataSourceService.getMetadataSourceList();
        Stream<MetadataSourceEntity> stream = sourceList.stream();
        if (StringUtils.isNotBlank(metadataColumnQuery.getSourceId())) {
            stream = stream.filter(s -> metadataColumnQuery.getSourceId().equals(s.getId()));
        }
        return stream.map(m -> {
            MetadataTreeVo tree = new MetadataTreeVo();
            tree.setId(m.getId());
            tree.setType(DataLevel.DATABASE.getKey());
            tree.setLabel(m.getSourceName());
            tree.setName(m.getSourceName());
            if (DataLevel.getLevel(level).getLevel() >= DataLevel.TABLE.getLevel()) {
                tree.setChildren(getTableChildrens(m.getId(), level, metadataColumnQuery.getTableId()));
            }
            return tree;
        }).collect(Collectors.toList());
    }

    private List<MetadataTreeVo> getTableChildrens(String id, String level, String tableId) {
        List<MetadataTableEntity> tableList = metadataTableService.getDataMetadataTableList(MetadataTableQuery.formSourceId(id));
        Stream<MetadataTableEntity> stream = Optional.ofNullable(tableList).orElseGet(ArrayList::new).stream();
        if (StringUtils.isNotBlank(tableId)) {
            stream = stream.filter(s -> tableId.equals(s.getId()));
        }
        return stream.map(m -> {
            MetadataTreeVo tree = new MetadataTreeVo();
            tree.setId(m.getId());
            tree.setType(DataLevel.TABLE.getKey());
            tree.setName(m.getTableComment());
            tree.setCode(m.getTableName());
            tree.setLabel(StringUtils.isBlank(m.getTableComment()) ? m.getTableName() : m.getTableComment());
            if (DataLevel.getLevel(level).getLevel() >= DataLevel.COLUMN.getLevel()) {
                tree.setChildren(getColumnChildrens(m.getId()));
            }
            return tree;
        }).collect(Collectors.toList());
    }

    private List<MetadataTreeVo> getColumnChildrens(String id) {
        List<MetadataColumnEntity> columnList = this.getDataMetadataColumnList(MetadataColumnQuery.formTableId(id));
        Stream<MetadataColumnEntity> stream = Optional.ofNullable(columnList).orElseGet(ArrayList::new).stream();
        return stream.map(m -> {
            MetadataTreeVo tree = new MetadataTreeVo();
            tree.setId(m.getId());
            tree.setType(DataLevel.COLUMN.getKey());
            tree.setName(m.getColumnComment());
            tree.setCode(m.getColumnName());
            tree.setLabel(StringUtils.isBlank(m.getColumnComment()) ? m.getColumnName() : m.getColumnComment());
            return tree;
        }).collect(Collectors.toList());
    }

    @Override
    public List<MetadataColumnEntity> getDataMetadataColumnList(MetadataColumnQuery metadataColumnQuery) {
        boolean admin = SecurityUtil.isAdmin();
        if (StringUtils.isBlank(metadataColumnQuery.getTableId())) {
            throw new DataException("数据表不能为空");
        }
        List<MetadataColumnEntity> columnList = this.getMetadataColumnByTableId(metadataColumnQuery.getTableId());
        Stream<MetadataColumnEntity> stream = Optional.ofNullable(columnList).orElseGet(ArrayList::new).stream();
        if (!admin) {
            List<String> roleIds = SecurityUtil.getUserRoleIds();
            Set<String> set = metadataAuthorizeService.authorities(roleIds, DataLevel.COLUMN.getKey()::equals);
            stream = stream.filter(s -> set.contains(s.getId()));
        }
        return stream.collect(Collectors.toList());
    }

    @Override
    public <E extends IPage<MetadataColumnEntity>> E pageWithAuth(E page, Wrapper<MetadataColumnEntity> queryWrapper) {
        boolean admin = SecurityUtil.isAdmin();
        List<String> roles = new ArrayList<>();
        if (!admin) {
            roles = SecurityUtil.getUserRoleIds();
        }
        return metadataColumnDao.selectPageWithAuth(page, queryWrapper, roles);
    }

    @Override
    public List<MetadataColumnEntity> getMetadataColumnByTableId(String tableId) {
        QueryWrapper<MetadataColumnEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MetadataColumnEntity::getTableId, tableId);
        return list(queryWrapper);
    }

    @Override
    public MetadataColumnEntity getMetadataColumnByTableIdAndColumnName(String table, String column) {
        QueryWrapper<MetadataColumnEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MetadataColumnEntity::getTableId, table)
                .eq(MetadataColumnEntity::getColumnName, column);
        return getOne(queryWrapper);
    }
}
